﻿using System;
using System.Threading.Tasks;
using Models;

namespace Client.Common
{
    public enum Steps
    {
        Send,
        Succ,
        Fail,
        Timeout
    }

    public class StateModel
    {
        public Steps CurStep { get; set; }
        public RetModel RM { get; set; }

        public string ErrStr
        {
            get
            {
                if (RM is null)
                    RM = new RetModel();
                return $"错误代码：{RM.ErrCode}\r\n错误信息：{RM.ErrInfo}";
            }
        }

        private long _curTick
        {
            get
            {
                return DateTime.UtcNow.Ticks / 10000000;
            }
        }

        private long _timeoutTick = 0;

        public void ResetTimeOut()
        {
            _timeoutTick = _curTick;
        }

        public long GetTimeout()
        {
            return _curTick - _timeoutTick;
        }

        public Task CheckState(int timeout)
        {
            ResetTimeOut();
            var x = Task.Run(() =>
            {
                while (CurStep == Steps.Send)
                {
                    if (GetTimeout() > timeout)
                    {
                        CurStep = Steps.Timeout;
                        RM = new RetModel { ErrCode = "0000", ErrInfo = "等待超时" };
                        break;
                    }
                    System.Threading.Thread.Sleep(10);
                }
            });
            return x;
        }
    }
}